package com.etbsms.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import com.etbsms.dao.ICodePlantDAO;
import com.etbsms.domain.CodePlant;

@Repository
@Component("codePlantDAO")
public class CodePlantDAOImpl extends GenericDAOImpl<CodePlant, String> 
	implements ICodePlantDAO {


	@Override
	@SuppressWarnings("unchecked")
	public List<CodePlant> getAll() {
		Session session = sessionFactory.openSession();
		Criteria criteria = session.createCriteria(CodePlant.class);
		//criteria.add(Restrictions.isNotNull("parent"));
		criteria.addOrder(Order.asc("parent"));
		List<CodePlant> list = criteria.list();
		session.close();
		return list;
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<CodePlant> query(String qr) {
		qr = "%" + qr + "%";		
		
		Session session = sessionFactory.openSession();
		Criteria criteria = session.createCriteria(CodePlant.class);
		criteria.add(Restrictions.isNotNull("parent"));
		
		Disjunction disj = Restrictions.disjunction();
		disj.add(Restrictions.ilike("name_en", qr));
		disj.add(Restrictions.ilike("name_ch", qr));
		criteria.add(disj);
						
		criteria.addOrder(Order.asc("parent"));
		List<CodePlant> list = criteria.list();
		session.close();
		return list;
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<CodePlant> getAll2() {
		Session session = sessionFactory.openSession();
		Criteria criteria = session.createCriteria(CodePlant.class);
		criteria.add(Restrictions.isNotNull("parent"));
		criteria.addOrder(Order.asc("parent"));
		List<CodePlant> list = criteria.list();
		session.close();
		return list;
	}

	@Override
	public String getMaxSeqNo() {
		Session session = sessionFactory.openSession();
		String hql = "select max(code) + 1 from CodePlant where parent is not null";
		Query query = session.createQuery(hql);
		return String.valueOf(query.list().get(0));	
	}
	

}
